package com.meepo.feed.old.essay

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import com.meepo.basic.router.RouterManager.FeedModule.FeedEssayPublish_Path
import com.meepo.basic.components.AlertPopup
import com.meepo.basic.components.ImagePopup
import com.meepo.basic.schema.Enums
import com.meepo.basic.schema.feed.ItemReq
import com.meepo.basic.schema.feed.Resource
import com.meepo.basic.components.view.SwipeBackUnSupportActivity
import com.meepo.feed.API
import com.meepo.feed.R
import com.meepo.framework.design.helper.ImageLoader
import com.meepo.framework.design.recycler.LinearAdapter
import com.meepo.framework.design.recycler.ViewHolder
import com.xiaojinzi.component.anno.RouterAnno
import com.yuyh.library.imgsel.ISNav
import com.yuyh.library.imgsel.config.ISListConfig
import kotlinx.android.synthetic.main.feed_publish_activity.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


@RouterAnno(hostAndPath = FeedEssayPublish_Path)
class EssayPublishActivity : SwipeBackUnSupportActivity() {



    private var mTitle: String = ""

    private lateinit var mAdapter: LinearAdapter<Any>

    override fun initData() {
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1022 && resultCode == Activity.RESULT_OK) {
            data?.getStringArrayListExtra("result")?.let {
                mAdapter.add(it)
            }
        }
        switchPublishButtonStatus()

    }

    private fun publish(paths: List<String>) {

        if (paths.isEmpty()) return

        val loadingPopup = XPopup.Builder(this)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asLoading("发布中")
            .show() as LoadingPopupView


        val builder = MultipartBody.Builder().setType(MultipartBody.FORM)

        for (element in paths) {
            val f = File(element)
            builder.addFormDataPart("files", f.name, RequestBody.create(MediaType.parse("application/octet-stream"), f))
        }

        val body = builder.build()

        presenter.call(
            API.instance().uploadFiles(body),
            { rsp ->
                rsp.data?.let {

                    val resources = arrayListOf<Resource>()
                    it.forEach { res -> resources.add(Resource(resourceType = Enums.MEDIA_TYPE_IMAGE, content = res)) }

                    presenter.call(
                        API.instance().publish(ItemReq(title = mTitle, topicId = "", resources = resources)),
                        { AlertPopup.popup(this, "发布成功"); finish() },
                        { AlertPopup.popup(this, "发布失败") }
                    )
                }
                loadingPopup.dismiss()
            },
            { loadingPopup.dismiss();AlertPopup.popup(this, "发布失败") }
        )
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {

        back_iv.setOnClickListener { finish() }

        publish_btn.setOnClickListener {
            publish(mAdapter.getAll())
        }

        title_et.requestFocus()
        title_et.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                mTitle = "" + (p0 ?: "").toString()
                switchPublishButtonStatus()
            }
        })

        images_recycler_view.layoutManager = GridLayoutManager(this, 3)
        images_recycler_view.itemAnimator = null // 取消更新闪烁

        mAdapter = object : LinearAdapter<Any>(this) {
            override fun getItemLayoutId(item: Any, position: Int): Int {
                return R.layout.feed_publish_activity_image_item
            }

            override fun bind(item: Any, holder: ViewHolder, position: Int) {

                holder.getView<ImageView>(R.id.cover_iv)?.let {


                    if (item is String) {
                        val uri: Uri = Uri.fromFile(File(item))
                        it.setImageURI(uri)

                        it.setOnClickListener {
                            ImagePopup.popup(this@EssayPublishActivity, it as ImageView, uri)
                        }

                    } else if (item is Int) {
                        it.setImageResource(item)
                    }
                }

                holder.getView<ImageView>(R.id.remove_iv)?.setOnClickListener {
                    remove(position, position)
                    switchPublishButtonStatus()
                }
            }
        }

        images_recycler_view.adapter = mAdapter

        // 底部按钮
        image_iv.setOnClickListener {

//            RxPermissions(this).request(Manifest.permission.CAMERA).subscribe { granted ->
//                Log.e("RxPermissions ", "granted " + granted)
//                if (granted) {
            // 自由配置选项
            ISNav.getInstance().init { context, path, imageView -> ImageLoader.loadImage(context, path, imageView) }

            // 自由配置选项
            val config = ISListConfig.Builder() // 是否多选, 默认true
                .multiSelect(true)
                .rememberSelected(false) // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .btnBgColor(Color.DKGRAY) // “确定”按钮背景色
                .btnTextColor(Color.WHITE) // “确定”按钮文字颜色
                .statusBarColor(Color.DKGRAY) // 使用沉浸式状态栏
                .backResId(R.drawable.ic_basic_back)  // 返回图标ResId
                .title("图片")// 标题
                .titleColor(Color.WHITE)// 标题文字颜色
                .titleBgColor(Color.DKGRAY) // TitleBar背景色
//                        .cropSize(1, 1, 200, 200)// 裁剪大小。needCrop为true的时候配置
//                        .needCrop(true)
                .needCamera(true) // 第一个是否显示相机，默认true
                .maxNum(1 - mAdapter.itemCount)// 最大选择图片数量，默认9
                .build()

            ISNav.getInstance().toListActivity(this, config, 1022)

//                }
//            }
        }

    }

    private fun switchPublishButtonStatus() {
        if (mAdapter.itemCount == 0 && mTitle.isEmpty()) {
            publish_btn.isEnabled = false
            publish_btn.alpha = 0.5f
        } else {
            publish_btn.isEnabled = true
            publish_btn.alpha = 1f
        }

    }

    override fun setUpContentLayout(): Int = R.layout.feed_publish_activity

}